package com.example.elmspringboot.config;


import com.example.elmspringboot.security.Jwt.JwtFilter;
import com.example.elmspringboot.security.realm.JwtShiroRealm;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;

/**
 * @author <a href="mailto:15268179013@139.com">yida</a>
 * @Version 2020-01-01 15:05
 * @Version 1.0
 * @Description ShiroConfig
 */
// 写入了manager
@Configuration
public class JwtShiroConfig {

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();

        //session管理
//        webSecurityManager.setSessionManager(sessionManager());

        //realm管理
        webSecurityManager.setRealm(realm());

        //缓存管理
        webSecurityManager.setCacheManager(new MemoryConstrainedCacheManager());
        //关闭session
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        webSecurityManager.setSubjectDAO(subjectDAO);

        return webSecurityManager;
    }


    @Bean
    public Realm realm() {
        JwtShiroRealm shiroRealm = new JwtShiroRealm();
        return shiroRealm;
    }

    // 设置shiro内置过滤器拦截范围(白名单)
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
//        shiroFilterFactoryBean.setLoginUrl("/login1"); // 设置跳转页
//        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setFilterChainDefinitions(
                "/api/user/login = anon\n" +
                "/api/businesses = anon\n" +
                "/swagger-ui/** = anon\n" + // 设置swagger
//                "/v3/api-docs/swagger-config = anon\n" + // 设置swagger
                        "/logout = logout\n" +
                        "/user = jwt,authc,perms[user:list]\n" +
                        "/** = jwt\n" +
                        "");

        HashMap<String, Filter> myFIleter = new HashMap<>();
        myFIleter.put("jwt", new JwtFilter());

        shiroFilterFactoryBean.setFilters(myFIleter);

        return shiroFilterFactoryBean;
    }

}

